<template>
  <div class="tree">
    <div class="tree-title">组织机构选择</div>
    <div class="tree-content">
      <a-config-provider
        :theme="{
          token: {
            borderRadius: 0,
          },
        }"
      >
        <a-input-search
          v-model:value="searchValue"
          style="margin-bottom: 8px"
          placeholder="输入关键字进行过滤"
          @search="handleSearch"
        />
      </a-config-provider>
      <div class="tree-wrap">
        <a-tree
          v-model:selectedKeys="selectedKeys"
          v-model:expandedKeys="expandedKeys"
          :tree-data="filterData"
          :field-names="{ children: 'child', title: 'orgName', key: 'orgId' }"
          @select="onSelect"
        >
          <template #title="{ orgName, count }">
            <span v-if="searchValue && orgName.indexOf(searchValue) > -1" style="color: blue">
              {{ orgName }} <span>({{ count }})</span>
            </span>
            <span v-else
              >{{ orgName }} <span>({{ count }})</span></span
            >
          </template>
        </a-tree>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import data from './data.json'

// 展开指定的树节点
const expandedKeys = ref<string[]>([])

// 设置选中的树节点
const selectedKeys = ref<string[]>()
let selectedKeysByFilter: string[] = []

// 树数据
let treeData: any = []
const filterData = ref<any[]>([])
// 查询数据
const searchValue = ref<string>('')

watch(() => searchValue.value, handleSearch)

getTreeData()

function onSelect(selectedKeys: any[], option: any) {
  console.log('🚀 ~ option:', option)
  let data = {
    oneUnitId: undefined,
    secUnitId: undefined,
    thirdUnitId: undefined,
    currentId: undefined,
  }
  if (selectedKeys.length) {
    const org = option.node
    if (org.orgLevel === 1) {
      data = {
        oneUnitId: org.orgId,
        secUnitId: undefined,
        thirdUnitId: undefined,
        currentId: undefined, // 后端要求一级单位，列表查询不传id
      }
    } else if (org.orgLevel === 2) {
      data = {
        oneUnitId: org.pid,
        secUnitId: org.orgId,
        thirdUnitId: undefined,
        currentId: org.orgId,
      }
    } else if (org.orgLevel === 3) {
      data = {
        oneUnitId: undefined,
        secUnitId: org.pid,
        thirdUnitId: org.orgId,
        currentId: org.orgId,
      }
    }
  }
}

function getTreeData() {
  treeData = JSON.parse(JSON.stringify(data))
  // filterData.value = treeData
  handleSearch()
}

function handleSearch() {
  if (searchValue.value) {
    selectedKeysByFilter = []

    filterData.value = filterTree(JSON.parse(JSON.stringify(treeData)), searchValue.value) || []
  } else {
    filterData.value = JSON.parse(JSON.stringify(treeData))
    if (treeData.length) {
      selectedKeysByFilter = [treeData[0].orgId]
    }
  }
  nextTick(() => {
    expandedKeys.value = selectedKeysByFilter
  })
  console.log('🚀 ~ selectedKeysByFilter:', selectedKeysByFilter)
}

function filterTree(nodes: any[], query: string) {
  const newChildren: any[] = []

  nodes.forEach(node => {
    // 以下两个条件任何一个成立，当前节点都应该加入到新子节点集中
    // 1. 子孙节点中存在符合条件的，即 subs 数组中有值
    // 2. 自己本身符合条件
    const child = filterTree(node.child || [], query)
    if (node.orgName.includes(query)) {
      newChildren.push(node)
    } else if (child.length) {
      node.child = child
      newChildren.push(node)
      selectedKeysByFilter.push(node.orgId)
    }
    // 以下只需要考虑自身的节点满足条件即可,不用带上父节点
    // if (node.orgName.includes(query)) {
    //   node.child = filterTree(node.child || [], query)
    //   newChildren.push(node)
    // } else {
    //   newChildren.push(...filterTree(node.child || [], query))
    // }
  })

  return newChildren
}

// 暴露state和play方法
defineExpose({
  getTreeData,
})
</script>

<style lang="scss" scoped>
.tree {
  width: 100%;
  height: 100%;
  border: 1px solid #f1f1f1;
  border-radius: 5px;

  .tree-title {
    display: flex;
    align-items: center;
    width: 100%;
    height: 45px;
    padding-left: 20px;
    font-size: 14px;
    font-weight: 650;
    color: #333;
    background: #f5f5f5;
    border-radius: 5px;
    border-bottom-right-radius: 0;
    border-bottom-left-radius: 0;
  }

  .tree-content {
    height: calc(100% - 45px);

    .tree-wrap {
      height: calc(100% - 50px);
      overflow: auto;
    }
  }

  // :deep(.ant-input) {
  //   height: 40px;
  //   border-left: 0;
  //   border-radius: 0;
  // }

  // :deep(.ant-input-search-button) {
  //   width: 40px;
  //   height: 40px;
  //   border-right: 0;
  //   border-left: 0;
  //   border-radius: 0 !important;
  // }

  // :deep(.ant-input-search) > .ant-input-group > .ant-input-group-addon:last-child {
  //   left: 0;
  // }
}
</style>
